package main

import (
	"html/template"
	"log"
	"net/http"
	"workspace/websocket/src/action"
	"workspace/websocket/src/global"
)

func main() {
	//加载配置文件
	err := global.LoadConfig()
	if err != nil {
		println(err.Error())
		return
	}

	//设置日志记录器
	err = global.SetLogger()
	if err != nil {
		println(err.Error())
		return
	}

	//启动websocket连接调度服务
	dispatcher := action.NewDispatcher()
	dispatcher.Start()

	//启动RPC服务
	go action.StartRPC(dispatcher)

	//注册websocket连接路由
	http.HandleFunc("/ws/price", func(w http.ResponseWriter, r *http.Request) {
		//处理websocket客户端连接处理器
		dispatcher.ConnectHandler(w, r)
	})

	//注册websocket客户端路由
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		if r.URL.String() != "/" {
			w.WriteHeader(404)
			w.Write([]byte("not found"))
			return
		}
		if err := template.Must(template.ParseFiles("templates/client.html")).Execute(w, nil); err != nil {
			w.Write([]byte(err.Error()))
		}
	})

	//注册websocket服务状态监控路由
	http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
		dispatcher.Status(w, r)
	})

	log.Println("启动服务")
	//启动http服务
	if err := http.ListenAndServe(":8888", nil); err != nil {
		global.Logger.Error(err.Error())
		return
	}
}
